import axios from 'axios'
import { Base64 } from 'js-base64';

function genWms(tiffPath) {

  const storeName1 = tiffPath.split('/').pop()

  let storeName1arr = storeName1.split(".")

  storeName1arr.pop()

  let storeName1res = storeName1arr.join('.')

  // const storeNameURL = storeName1res
  const storeNameURL1 = Base64.encode(storeName1res)
  // const storeNameURL = encodeURIComponent(storeNameURL1)
  const storeNameURL = storeNameURL1

  // GeoServer 配置
  const GEOSERVER_CONFIG  = {
    baseURL: '/geoserver/rest',
    auth: {
      username: 'admin',
      password: 'geoserver'
    },
    workspace: 'test_tif',  // 自定义工作区名称
    storeName: storeName1,  // 存储名称
    filePath: `file:///${tiffPath}`, // 支持 file/http/ftp 协议
    crs: 'EPSG:4326'           // 目标坐标系
  };

  // 创建认证客户端
  const api = axios.create({
    baseURL: GEOSERVER_CONFIG.baseURL,
    auth: GEOSERVER_CONFIG.auth,
    headers: {
      'Content-Type': 'text/plain' // 关键头信息
    }
  });

  publishTiff(GEOSERVER_CONFIG.storeName)

  async function publishTiff(layerName) {
    try {
      // 1. 创建或验证工作区
      // await createWorkspace();

      // 2. 创建外部关联的 CoverageStore
      const storeUrl = `/workspaces/${GEOSERVER_CONFIG.workspace}/coveragestores/${storeNameURL}/external.geotiff`;

      await api.put(storeUrl, GEOSERVER_CONFIG.filePath);

      // 3. 设置坐标系
      await setLayerCRS();

      console.log(`图层 ${storeName1} 发布成功`);
    } catch (error) {
      handleError(error);
    }
  }


  // 设置坐标系
  async function setLayerCRS() {
    const coverageConfig = {
      coverage: {
        name: storeNameURL,
        // parameters: {
        //   'NODATA': 0,
        // },
          'NoData': 0,
        // srs: GEOSERVER_CONFIG.targetCRS,
        nativeCRS: GEOSERVER_CONFIG.crs, // 强制指定原生坐标系
        // nativeCRS: GEOSERVER_CONFIG.targetCRS, // 强制指定原生坐标系
        enabled: true
      }
    };

    const xmlData = `
          <coverage>
            <name>${storeNameURL}</name>
            <nativeCoverageName>${storeNameURL}</nativeCoverageName>
            <parameters>
              <entry>
                <string>InputTransparentColor</string>
                <string>255</string>
              </entry>
            </parameters>
          </coverage>
        `;

    await api.post(
      `/workspaces/${GEOSERVER_CONFIG.workspace}/coveragestores/${storeNameURL}/coverages`,
      coverageConfig,
      { headers: { 'Content-Type': 'application/json' } }
    );

    // await api.put(
    //   `/workspaces/${GEOSERVER_CONFIG.workspace}/coveragestores/${storeNameURL}/coverages/${storeNameURL}`,
    //   xmlData,
    //   { headers: { 'Content-Type': 'application/xml' } }
    // );

  }

}

export { genWms }